<?php
/**
 * Created by lzl
 * Date: 2021 2021/11/10
 * Time: 17:04
 */
namespace App\Utils;


class Express
{

    public $express_sn;  //物流单号

    public $shipper_code; //快递公司编码

    public $customer_name = ''; //ShipperCode 为JD，必填，对应京东的青龙配送编码，也叫商家编码，格式：数字＋字母＋数字，9 位数字加一个字母，共10 位，举例：001K123450；ShipperCode 为SF，且快递单号非快递鸟渠道返回时，必填，对应收件人/寄件人手机号后四位；

    public function search()
    {
        // 组装应用级参数
        $requestData= [
            'ShipperCode'  => $this->shipper_code, //快递公司编码
            'CustomerName' => $this->customer_name,
            'LogisticCode' => $this->express_sn, //物流单号
        ];

        // 组装系统级参数
        $data = [
            'EBusinessID' => config('kdn.app_id'),
            'RequestType' => '1002',
            'RequestData' => urlencode(json_encode($requestData)) ,
            'DataType' => '2',
        ];

        $data['DataSign'] = $this->encrypt(json_encode($requestData), config('kdn.app_key'));

        $result = $this->sendPost(config('kdn.url.search'), $data);

        return $result;
    }


    /**
     * post提交数据
     * @param $url
     * @param $datas
     * @return false|string
     */
    function sendPost($url, $data) {
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => http_build_query($data),
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result, true);
    }


    /**
     * 电商Sign签名生成
     * @param $data
     * @param $ApiKey
     * @return string
     */
    function encrypt($data, $ApiKey) {
        return urlencode(base64_encode(md5($data.$ApiKey)));
    }

}
